import api from '@/api'
import { deepCopy, setPage } from '@/utils/util'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null
    }
}

// state
const state = {
    data: {
        videos: [],
        classVideo: []
    },
    ui: {
        page: deepCopy(initPage)
    }
}

// getters
const getters = {
    videos: state => state.data.videos,
    classVideo: state => state.data.classVideo,

    videosTotal: state => state.ui.page.total
}

// actions
const actions = {

    getVideos({ state, commit }, params = {}) {
        api.getVideos({
            loading: params.loading === false ? false : true,
            method: 'post',
            data: JSON.stringify(params) != "{}" ? params : state.ui.page,
            success: (res) => {
                const { pages, total } = res
                commit('SETVIDEOPAGE', { pages, total })

                let videos = res.content
                commit('SETVIDEOS', { videos })
            }
        })
    },

    removeVideo({ dispatch }, params = {}) {
        api.removeVideo({
            method: 'post',
            data: params,
            success: (res) => {
                dispatch('getVideos')
            }
        })
    },

    addVideo({ dispatch }, params) {
        api.addVideo({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getVideos')
            }
        })
    },

    editVideo({ dispatch }, params) {
        api.editVideo({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getVideos')
            }
        })
    },

    getClassVideo({ commit }, params) {
        api.classVideo({
            method: 'get',
            data: params,
            success: (res) => {
                let classVideo = res
                commit('SETCLASSVIDEO', { classVideo })
            }
        })
    }
}

// mutations
const mutations = {

    SETVIDEOS(state, payload) {
        state.data.videos = payload.videos
    },

    SETCLASSVIDEO(state, payload) {
        state.data.classVideo = payload.classVideo
    },

    SETVIDEOPAGE(state, page) {
        page && setPage(state.ui.page, page)
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}